package it.kion.util.ui.ulog2;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.log4j.spi.LoggingEvent;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.Viewer;

public class LoggingModel implements IStructuredContentProvider {
	
	private List<ILoggingEventListener> listenerList = new ArrayList<ILoggingEventListener>();
	private List<LoggingEvent> allLogs = new ArrayList<LoggingEvent>();
	private List<LoggingEvent> events = new ArrayList<LoggingEvent>() {

		private static final long serialVersionUID = 5363544406901923547L;

		@Override
		public void clear() {
			super.clear();
			for(ILoggingEventListener ll : listenerList) {
				ll.handleClear();
			}
		}
	};
	private List<LoggingEvent> hidden_events = new ArrayList<LoggingEvent>();
	
	private final FilterSet filterSet = new FilterSet();
	
	public FilterSet getFilterSet() {
		return filterSet;
	}

	public void addListener(ILoggingEventListener listener) {
		listenerList.add(listener);
	}

	public void removeListener(ILoggingEventListener listener) {
		listenerList.remove(listener);
	}

	public void addEvent(LoggingEvent event) {
		if(!Log4jPlugin.isPaused()) {
			if (getFilterSet().isValidForShow(event) /*&& Log4jPlugin.getDefault().isShowing()*/) {
				if(events.size()==0) {
					allLogs.add(event);
					addShowingEvent(event);
				} else {
					addShowingEvent(0, event);
				}
			}			
		} else {
			hidden_events.add(0, event);
		}
	}

	private void addShowingEvent(int index, LoggingEvent event) {
		addShowingEvent(index, event, true);
	}

	private void addShowingEvent(LoggingEvent event) {
		addShowingEvent(null, event, true);
	}
	
	public LoggingEvent getLoggingEventShowingAt(int idx) {
		return events.get(idx);
	}
	
	private void addShowingEvent(Integer index, LoggingEvent event, boolean processListeners) {
		if(index==null) {
			events.add(event);	
		} else {
			events.add(index, event);
		}
		if(processListeners) {
			for (ILoggingEventListener lel : listenerList) {
				lel.handleEvent(event);
			}
		}
	}

	public void clear() {
		events.clear();
		hidden_events.clear();
	}

	public Object[] getElements(Object inputElement) {
		return events.toArray();
	}

	public void dispose() {
	}

	public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
	}
	
	public void revalidateAll() {
		events.clear();
		hidden_events.clear();
		for (LoggingEvent thisEvent : allLogs) {
			if (Log4jPlugin.getDefault().getLoggingModel().getFilterSet().isValidForShow(thisEvent)) {
				addShowingEvent(0, thisEvent);
			}
		}
	}

	public Collection<LoggingEvent> getValidLogs() {
		ArrayList<LoggingEvent> rSet = new ArrayList<LoggingEvent>();
		if (!Log4jPlugin.isPaused()) {
			rSet.addAll(hidden_events);
		}
		rSet.addAll(events);
		return rSet;
	}

}
